package com.hzzftech.watchdog.busi.controller;

import java.io.File;
import java.util.List;

import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.core.file.repository.KtFileRepositoryFileParser;
import com.hzzftech.watchdog.busi.domain.KtFileRepositoryMsg;
import com.hzzftech.watchdog.busi.service.IKtFileRepositoryMsgService;
import com.hzzftech.watchdog.busi.utils.FileUtils;
import com.hzzftech.watchdog.common.core.text.Convert;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hzzftech.watchdog.common.annotation.Log;
import com.hzzftech.watchdog.common.enums.BusinessType;
import com.hzzftech.watchdog.busi.domain.KtFileVersion;
import com.hzzftech.watchdog.busi.service.IKtFileVersionService;
import com.hzzftech.watchdog.common.core.controller.BaseController;
import com.hzzftech.watchdog.common.core.domain.AjaxResult;
import com.hzzftech.watchdog.common.utils.poi.ExcelUtil;
import com.hzzftech.watchdog.common.core.page.TableDataInfo;

/**
 * 文件版本信息Controller
 * 
 * @author kt-watchdog
 * @date 2021-12-09
 */
@Controller
@RequestMapping("/busi/file/version")
public class KtFileVersionController extends BaseController
{
    private String prefix = "busi/file/version";

    @Autowired
    private IKtFileVersionService ktFileVersionService;

    @RequiresPermissions("busi:version:view")
    @GetMapping()
    public String version()
    {
        return prefix + "/version";
    }

    /**
     * 查询文件版本信息列表
     */
    @RequiresPermissions("busi:version:list")
    @PostMapping("/list/{repoId}/{fileId}")
    @ResponseBody
    public TableDataInfo list(@PathVariable("repoId") Long repoId,@PathVariable("fileId") Long fileId, KtFileVersion ktFileVersion)
    {
        startPage();
        ktFileVersion.setRepoId(repoId);
        ktFileVersion.setFileId(fileId);
        List<KtFileVersion> list = ktFileVersionService.selectKtFileVersionList(ktFileVersion);
        return getDataTable(list);
    }

    /**
     * 导出文件版本信息列表
     */
    @RequiresPermissions("busi:version:export")
    @Log(title = "文件版本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(KtFileVersion ktFileVersion)
    {
        List<KtFileVersion> list = ktFileVersionService.selectKtFileVersionList(ktFileVersion);
        ExcelUtil<KtFileVersion> util = new ExcelUtil<KtFileVersion>(KtFileVersion.class);
        return util.exportExcel(list, "文件版本信息数据");
    }

    /**
     * 新增文件版本信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件版本信息
     */
    @RequiresPermissions("busi:version:add")
    @Log(title = "文件版本信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(KtFileVersion ktFileVersion)
    {
        return toAjax(ktFileVersionService.insertKtFileVersion(ktFileVersion));
    }

    /**
     * 修改文件版本信息
     */
    @RequiresPermissions("busi:version:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        KtFileVersion ktFileVersion = ktFileVersionService.selectKtFileVersionById(id);
        mmap.put("ktFileVersion", ktFileVersion);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件版本信息
     */
    @RequiresPermissions("busi:version:edit")
    @Log(title = "文件版本信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(KtFileVersion ktFileVersion)
    {
        return toAjax(ktFileVersionService.updateKtFileVersion(ktFileVersion));
    }

    @Autowired
    private IKtFileRepositoryMsgService msgService;

    @Value("${kt-watchdog.file_repository_location}")
    private String FILE_REPOSITORY_LOCATION;

    /**
     * 删除文件版本信息
     */
    @RequiresPermissions("busi:version:remove")
    @Log(title = "文件版本信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ktFileVersionService.deleteKtFileVersionByIds(ids));
    }


    @ResponseBody
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(KtFileVersion version) {
        if (version.getId() == null) {
            return AjaxResult.error("切换版本错误");
        }
        KtFileVersion ktFileVersion = ktFileVersionService.selectKtFileVersionById(version.getId());
        if (ktFileVersion == null) {
            return AjaxResult.error("未找到版本信息");
        }

        if (ktFileVersion.get_enable().equals(BusiConstant.FILE_VERSION_ENABLE_YES)) {
            return AjaxResult.error("当前版本正在使用");
        }

        KtFileRepositoryFileParser parser = new KtFileRepositoryFileParser(
                msgService, ktFileVersionService, ktFileVersion.getRepoId(),FILE_REPOSITORY_LOCATION
        );

        // 文件路径
        String filePath = FILE_REPOSITORY_LOCATION+parser.getFilePath(msgService.selectKtFileRepositoryMsgById(ktFileVersion.getFileId()));
        FileUtils.deleteFile(filePath);
        FileUtils.copyFile(FILE_REPOSITORY_LOCATION+ File.separator +"version_"+ktFileVersion.getRepoDirect()+File.separator+ktFileVersion.getVersion(), filePath);

        KtFileRepositoryMsg msg = msgService.selectKtFileRepositoryMsgById(ktFileVersion.getFileId());
        // 当前正在使用的版本
        String currentVersion = msg.getEnableVersion();
        msg.setEnableVersion(ktFileVersion.getVersion());
        msgService.updateKtFileRepositoryMsg(msg);

        // 更新为新版本
        KtFileVersion ktFileVersionCurrent = ktFileVersionService.selectKtFileVersionByVersion(currentVersion);
        ktFileVersionCurrent.set_enable(BusiConstant.FILE_VERSION_ENABLE_NO);
        ktFileVersionService.updateKtFileVersion(ktFileVersionCurrent);

        ktFileVersion.set_enable(BusiConstant.FILE_VERSION_ENABLE_YES);
        ktFileVersionService.updateKtFileVersion(ktFileVersion);

        return AjaxResult.success();
    }
}
